package com.leetcode.hot100;

import java.util.Arrays;

/**
 * @BelongsProject: LeetCode
 * @BelongsPackage: com.leetcode.hot100
 * @Author: lei
 * @CreateTime: 2024-03-28  09:27
 * @Description: TODO
 * @Version: 1.0
 */
public class 除自身以外数组的乘积 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4};
        //int[] nums = {-1, 1, 0, -3, 3};
        System.out.println(Arrays.toString(productExceptSelf(nums)));

    }

/*    public static int[] productExceptSelf(int[] nums) {
        int[] answer = new int[nums.length];
        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums.length; j++) {
                if (i == j) continue;
                int num = nums[j];
                if (num != 0) {
                    result = result == 0 ? num : result * num;
                } else {
                    result = 0;
                    break;
                }
            }
            answer[i] = result;
            result = 0;
        }
        return answer;
    }*/

    public static int[] productExceptSelf(int[] nums) {
        int length = nums.length;
        int[] answer = new int[length];
        answer[0] = 1;
        for (int i = 1; i < answer.length; i++) {
            answer[i] = answer[i - 1] * nums[i - 1];
        }
        int temp = 1;
        // 24 12 4 1
        for (int i = length - 2; i >= 0; i--) {
            temp *= nums[i + 1];
            System.out.println(temp);
            answer[i] *= temp;
        }


        return answer;
    }

}
